<?php
namespace Wap\Controller;

use Think\Controller;
use Wap\Model;
use Wap\Service\CustomerService;
use Wap\Service\SessionService;
use Wap\Service\UUIDService;
use Common\Service\Sms\ShortMessageService;

class UserController extends Controller
{
	/**
	 *函数名: login
	 *函数描述: 用户登录
	 *@param json 登录号码、登录密码
	 *@return json 登录结果信息
	 */
	public function login()
	{
		$result	=	array( "error" => 0, "msg" => "登录信息错误！" );
		$loginTelephone	=	I( "loginTelephone", "", "" );
		$loginPassword	=	I( "loginPassword", "", "" );
		if( empty( $loginPassword ) || empty( $loginTelephone ) ){//TODO: 验证手机号码格式
			$result['error'] = 1;
			$result['msg'] = "用户名或密码不能为空";
			return $this->ajaxReturn( $result );
		}

		// $mode	=	D( "Uploader" );
		$mode	=	D( "Customer" );
        $condition = array( "telephone" => $loginTelephone, "password" => md5( $loginPassword ) );
		// $exist = $mode->where( $condition )->find();
		$exist = $mode->where( $condition )->getField("id");
        //S( "debug_exist", $exist, "" );
		if( $exist != null ){
            // CustomerService::setID( $exist['id'] );//更新当前用户id
            CustomerService::setID( $exist );//更新当前用户id
			$result['error'] = 0;
			$result['user'] = $exist;
			$result['msg']	= "登录成功";
		}else{
			$this->logout();
			$result['error'] = 1;
			$result['msg'] = "用户名或密码错误";
		}
		return $this->ajaxReturn( $result );
	}

	/**
	 *函数名: logout
	 *函数描述: 用户登出
	 *@return string 提示信息
	 */
	public function logout()
	{

        CustomerService::setOpenID( null );
        CustomerService::setID( null );
        //CustomerService::setOpenID( null );
	}

	/**
	 *函数名: registe
	 *函数描述: 用户注册
	 *@param json 用户注册信息
	 *@return json 用户注册结果
	 */
	public function registe()
	{
		$result	=	array( "error" => 0, "msg" => "registe", "validate" => array() );
		$registeTelephone	=	I( "post.registeTelephone", "", "" );
		$registePassword	=	I( "post.registePassword", "", "" );
		$smscode			=	I( "post.smscode", "", "" );
		$registeName		=	I( "post.registeName", "", "" );

		//判断手机号码格式是否正确、密码长度
		if( preg_match( "/^1\d{10}$/", $registeTelephone ) !== 1 || strlen($registePassword) != 6 )
		{
			$result['error'] = 1;
			$result['msg'] = "手机号码或密码格式错误";
			return $this->ajaxReturn( $result );//TODO: 手机号码格式是否错误
		}

		//判断手机号码有没有注册过
		// $mode	=	D( "uploader" );
		$mode	=	D( "customer" );
		$exist	=	$mode->where( "telephone = %s", array( $registeTelephone ) )->find();
		if( $exist ){
			$result['error'] = 1;
			$result['msg']	=	"号码已经注册过了";
			return $this->ajaxReturn( $result );
		}

        //$session_id = S( "debug_sessionid" ) ? S( "debug_sessionid" ) : array();
        //$session_id = array_push( $session_id, session_id() );
        //S( "debug_sessionid", $session_id, 3600 );

		//判断短信验证码是否正确
		//$_smscode = SessionService::get_smscode( $registeTelephone, 30 );
		$sms = SessionService::get_smscode( $registeTelephone, 60 );
		//if( ($smscode) || $smscode != $_smscode ){
		if( $sms['code'] === 204 || empty( $sms['code'] ) || $sms['code'] != $smscode ){
			$result['error'] = 1;
			$result['msg']	=	"验证码信息有误";
            $result['sms'] = $sms;
			return $this->ajaxReturn( $result );//
		}

		//获取openid
        $openid = CustomerService::getOpenID();
		if( !$openid ){
			$result['error'] = 1;
			$result['msg'] = "页面过期，请刷新页面";
			return $this->ajaxReturn( $result );
		}

		//执行注册
		// $mode = D( 'Uploader' );
		$mode = D( 'Customer' );
		// $uploader = array( "name" => $registeName, "telephone" => $registeTelephone, "password" => md5($registePassword), "add_time" => time(), "wecha_id" => $openid );
		$customer = array( "username" => $registeName, "telephone" => $registeTelephone, "password" => md5($registePassword), "create_time" => time(), "wecha_id" => $openid );
		// $saved = $mode->add( $teacher  );
		$saved = $mode->registe( $customer );
		if( !$saved['success'] ){
			$result['error'] = 1;
			$result['msg'] = $saved['msg'];
			return $this->ajaxReturn( $result );
		}else{
            CustomerService::setID( $saved['data']['id'] );
            S( "debug_customer", array( CustomerService::getID(), $saved ), 600 );
			$result['user'] = $saved['data']['id'];
			return $this->ajaxReturn( $result );
		}
	}

	/**
	 *函数名: smscode
	 *函数描述: 获取短信验证码
	 *@param string $_POST['regisTetelephone'] 用户注册手机号码
	 *@return json 验证码获取结果
	 */
	public function smscode()
	{
		$result	=	array( "error" => 1, "msg" => "发送出错" );
		$telephone	=	I( "post.registeTelephone", "", "" );

        $openid = CustomerService::getOpenID();
		if( !$openid ){
			$result['error'] = 1;
			$result['msg'] = "页面过期，请刷新页面";
			return $this->ajaxReturn( $result );
		}

		if( empty($telephone) ){
			$result['error'] = 1;
			$result['msg']	= "手机号码不能为空";
			return $this->ajaxReturn( $result );
		}

		$mode	=	D( "customer" );
		$exist	=	$mode->where( "telephone = %s", array( $telephone ) )->find();
		if( $exist ){
			$result['error'] = 2;
			$result['msg'] = "手机号码已经注册过了";
			return $this->ajaxReturn( $result );
		}

		$sms = SessionService::get_smscode( $telephone, 30 );//TODO: 短信时间30s
		if( $sms['error'] === 204 ){
			$code = UUIDService::generate_num( 6 );
            $msg = sprintf( "ESM 系统注册验证码 %d", $code );
			$sms = new ShortMessageService();
        	$sended =  $sms->sendMsgTo( $telephone, $msg );
			// $code = 123;
			// $sended = true;
			if( $sended ){
                SessionService::set_smscode( $telephone, $code );
				$result['error'] = 0;
				$result['msg'] = '发送成功';
			}
		}else if( $sms['error'] === 302 ){
			$result['error'] = 1;
			$result['msg']	=	"验证码未失效";
		}

		return $this->ajaxReturn( $result );
	}

	/**
	 *函数名: check
	 *函数描述: 判断用户是否在线
	 *@return json 在线信息
	 */
	public function check()
	{
		$result	= array( "online" => 0 );
		// $id	= SessionService::get_uploader();

		// $openid = session( "wxuser.openid" );//TODO: could be more simple
		// $uploader = 0;
		// if( $openid )
		// {
		// 	$uploader = D( "uploader" )->where( array("wecha_id" => $openid ) )->find();
		// }
		// if( $id != null || ( $openid != null && $uploader ) ){
		// 	$result['online'] = 1;
		// }
		//$customer_id = CustomerService::getID();
		//$result['online'] = $customer_id ? 1 : 0;
        $result['online'] = CustomerService::check();
		return $this->ajaxReturn( $result );
	}

 //    /**
	//  *函数名: home
	//  *函数描述: 注册用户个人主页、查看个人上传信息 not need
	//  */
	// public function home()//TODO: delete
	// {
	// 	$result	=	array( );
	// 	$id	=	SessionService::get_uploader();
	// 	if( empty( $id ) || $id == null ){
	// 		return $this->error( "用户不在线", "/show/index", 5  );
	// 	}

	// 	// $mode	=	D( "uploader" );
	// 	$mode	=	D( "customer" );
	// 	$result['user']	=	$mode->where( "id = %d", array( $id ) )->find();
	// 	if( count( $result['user'] ) <= 0 ){
	// 		return $this->error( "用户存在", 5 );
	// 	}
	// 	$this->assign( "user", $result['user'] );
	// 	$this->display( "Teacher/teacherdetail" );
	// }
}
?>
